<template>
  <div class="product-detail-container">
    <div class="product-detail-wrapper">
      <!-- 左侧商品图片区域 -->
      <div class="product-gallery">
        <div class="main-image" :style="{ backgroundImage: `url(${currentImage || defaultImage})` }"></div>
        <div class="thumbnail-list">
          <div 
            v-for="(img, index) in productImages" 
            :key="index"
            class="thumbnail" 
            :class="{ active: currentImage === img }"
            :style="{ backgroundImage: `url(${img})` }"
            @click="currentImage = img"
          ></div>
        </div>
      </div>

      <!-- 右侧商品信息区域 -->
      <div class="product-info">
        <h1 class="product-title">{{ product.title }}</h1>
        <div class="product-price">¥{{ product.price }}</div>
        
        <div class="product-meta">
          <div class="meta-item">
            <el-icon><Timer /></el-icon>
            <span>发布于 {{ formatTime(product.creationTime) }}</span>
          </div>
          <div class="meta-item">
            <el-icon><View /></el-icon>
            <span>浏览 {{ viewCount }} 次</span>
          </div>
        </div>

        <div class="seller-info">
          <div class="seller-avatar" :style="{ backgroundImage: `url(${sellerAvatar || defaultAvatar})` }"></div>
          <div class="seller-details">
            <div class="seller-name">{{ sellerName || '用户' + product.sellerID }}</div>
            <div class="seller-stats">卖家信用: <span class="rating">⭐⭐⭐⭐⭐</span></div>
          </div>
        </div>

        <div class="divider"></div>

        <div class="product-description">
          <h3>商品详情</h3>
          <p>{{ product.description }}</p>
          <div class="product-attributes">
            <div class="attribute">
              <span class="label">商品状态:</span>
              <span class="value">{{ getStatusText(product.status) }}</span>
            </div>
            <div class="attribute">
              <span class="label">商品成色:</span>
              <span class="value">{{ product.condition || '9成新' }}</span>
            </div>
            <div class="attribute">
              <span class="label">购买渠道:</span>
              <span class="value">{{ product.purchaseChannel || '正规渠道' }}</span>
            </div>
            <div class="attribute">
              <span class="label">转手原因:</span>
              <span class="value">{{ product.reason || '闲置' }}</span>
            </div>
          </div>
        </div>

        <div class="action-buttons">
          <button class="chat-button" @click="contactSeller">
            <el-icon><ChatDotRound /></el-icon>
            联系卖家
          </button>
          <button class="buy-button" @click="buyNow" :disabled="product.status === 'sold'">
            <el-icon><ShoppingCart /></el-icon>
            {{ getBuyButtonText() }}
          </button>
        </div>
      </div>
    </div>

    <!-- 相关商品推荐 -->
    <div class="related-products">
      <h2 class="section-title">相关推荐</h2>
      <div v-if="loading" class="loading-container">
        <el-skeleton :rows="1" animated />
      </div>
      <div v-else class="related-products-list">
        <div v-for="item in relatedProducts" :key="item.itemID" class="related-product-item"
          @click="goToDetail(item.itemID)">
          <div class="product-image" :style="{ backgroundImage: `url(${item.imageUrl || defaultImage})` }">
            <div class="product-price">¥{{ item.price }}</div>
          </div>
          <div class="product-info">
            <div class="product-title">{{ item.title }}</div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { Location, Timer, View, ChatDotRound, ShoppingCart, Star } from '@element-plus/icons-vue';
import { SecondHandItemApi } from '@/api/SecondHandItemApi.js';
import { MarketItemApi } from '@/api/new/MarketItemApi.ts';
import { ChatSessionApi } from '@/api/ChatSessionApi.js';
import { UserProfileApi } from '@/api/new/userProfleApi.js';
import UserUtil from '@/utils/User/User.js';

const route = useRoute();
const router = useRouter();
const itemID = computed(() => Number(route.params.id));

// 商品信息
const product = ref({});
const productImages = ref([]);
const currentImage = ref('');
const sellerName = ref('');
const sellerAvatar = ref('');
const sellerCreditScore = ref(0);
const viewCount = ref(0);
const loading = ref(true);
const relatedProducts = ref([]);

// 默认图片
const defaultImage = 'https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png';
const defaultAvatar = 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png';



// 获取商品详情
const fetchProductDetail = async () => {
  loading.value = true;
  try {
    // 获取商品基本信息
    const response = await SecondHandItemApi.getSecondHandItemById(itemID.value);
    product.value = response.data || {};
    
    // 获取商品图片
    const imagesResponse = await MarketItemApi.getItemImages(itemID.value);
    if (imagesResponse && Array.isArray(imagesResponse) && imagesResponse.length > 0) {
      productImages.value = imagesResponse.map(img => img.imageUrl);
      currentImage.value = productImages.value[0];
    } else if (imagesResponse && imagesResponse.imageUrl) {
      productImages.value = [imagesResponse.imageUrl];
      currentImage.value = imagesResponse.imageUrl;
    }
    
    // 获取卖家信息
    if (product.value && product.value.sellerID) {
      await fetchSellerInfo(product.value.sellerID);
    }
    
    // 模拟浏览次数
    viewCount.value = Math.floor(Math.random() * 100) + 50;
    
    // 获取相关推荐
    fetchRelatedProducts();
  } catch (error) {
    ElMessage.error(`获取商品详情失败: ${error.message}`);
  } finally {
    loading.value = false;
  }
};

// 获取卖家信息
const fetchSellerInfo = async (sellerId) => {
  try {
    // 使用UserProfileApi获取用户信息
    const userData = await UserProfileApi.getUserInfo(sellerId);
    
    // 更新卖家信息，使用正确的字段名
    sellerName.value = userData.username || '未知用户';
    sellerAvatar.value = userData.headshot || defaultAvatar;
    sellerCreditScore.value = userData.creditScore || 0;
  } catch (error) {
    console.error(`获取卖家 ${sellerId} 信息失败:`, error);
    // 设置默认值
    sellerName.value = '未知用户';
    sellerAvatar.value = defaultAvatar;
    sellerCreditScore.value = 0;
  }
};

// 获取相关推荐
const fetchRelatedProducts = async () => {
  try {
    const response = await SecondHandItemApi.getAllSecondHandItems();
    const items = response.data || [];
    
    // 过滤掉当前商品，并最多显示4个
    const filteredItems = items
      .filter(item => item.itemID !== itemID.value)
      .slice(0, 4);
    
    // 获取每个商品的图片
    const itemsWithImages = await Promise.all(
      filteredItems.map(async (item) => {
        try {
          const imageResponse = await MarketItemApi.getItemImages(item.itemID);
          let imageUrl = defaultImage;
          
          if (imageResponse && Array.isArray(imageResponse) && imageResponse.length > 0) {
            imageUrl = imageResponse[0].imageUrl;
          } else if (imageResponse && imageResponse.imageUrl) {
            imageUrl = imageResponse.imageUrl;
          }
          
          return { ...item, imageUrl };
        } catch (error) {
          return { ...item, imageUrl: defaultImage };
        }
      })
    );
    
    relatedProducts.value = itemsWithImages;
  } catch (error) {
    console.error('获取相关推荐失败:', error);
  }
};

// 格式化时间
const formatTime = (timeStr) => {
  if (!timeStr) return '未知时间';
  
  const now = new Date();
  const time = new Date(timeStr);
  const diff = Math.floor((now - time) / 1000); // 秒数差
  
  if (diff < 60) {
    return '刚刚';
  } else if (diff < 3600) {
    return Math.floor(diff / 60) + '分钟前';
  } else if (diff < 86400) {
    return Math.floor(diff / 3600) + '小时前';
  } else if (diff < 2592000) {
    return Math.floor(diff / 86400) + '天前';
  } else {
    return `${time.getFullYear()}-${time.getMonth() + 1}-${time.getDate()}`;
  }
};

// 获取状态文本
const getStatusText = (status) => {
  switch (status) {
    case 'forSale':
      return '在售';
    case 'inTransaction':
      return '交易中';
    case 'sold':
      return '已售出';
    default:
      return '未知';
  }
};

// 获取购买按钮文本
const getBuyButtonText = () => {
  if (!product.value) return '立即购买';
  
  switch (product.value.status) {
    case 'forSale':
      return '立即购买';
    case 'inTransaction':
      return '已预订';
    case 'sold':
      return '已售出';
    default:
      return '立即购买';
  }
};

// 立即购买
const buyNow = async () => {
  if (!product.value || product.value.status !== 'forSale') {
    ElMessage.warning('该商品已不可购买');
    return;
  }
  
  const userInfo = await UserUtil.getUserInfo();
  if (!userInfo || !userInfo.userID) {
    ElMessage.warning('请先登录');
    return;
  }
  
  // 跳转到确认订单页面
  router.push(`/secondhand/confirm/${itemID.value}`);
};

// 联系卖家
const contactSeller = async () => {
  const userInfo = await UserUtil.getUserInfo();
  if (!userInfo || !userInfo.userID) {
    ElMessage.warning('请先登录');
    return;
  }
  
  try {
    // 创建聊天会话
    const response = await MarketItemApi.createChatSession(userInfo.userID, product.value.sellerID, itemID.value);
    const res = JSON.parse(response);
    
    if (res.status === 'error') {
      console.log('触发了聊天创建的error');
      console.log('尝试通过用户id获取聊天id');
      
      // 使用 ChatSessionApi 获取已存在的聊天会话
      try {
        const chatSession = await ChatSessionApi.getChatSessionByUserIds(userInfo.userID, product.value.sellerID);
        if (chatSession && chatSession.chatSessionID) {
          // 跳转到聊天页面，使用正确的参数名 chatSessionID
          router.push(`/chat?chatSessionID=${chatSession.chatSessionID}&otherUserID=${product.value.sellerID}`);
        } else {
          ElMessage.error('无法获取聊天会话');
        }
      } catch (error) {
        ElMessage.error(`获取聊天会话失败: ${error.message}`);
      }
    } else if (res.status === 'success' && res.chatSession) {
      console.log('聊天创建成功', res);
      // 使用返回的 chatSession 对象中的 chatSessionID
      router.push(`/chat?chatSessionID=${res.chatSession.chatSessionID}&otherUserID=${product.value.sellerID}`);
    } else {
      ElMessage.error('创建聊天会话失败：返回数据格式不正确');
    }
  } catch (error) {
    ElMessage.error(`创建聊天失败: ${error.message}`);
  }
};

// 跳转到详情页 - 优化：使用replace而非push以优化导航历史
const goToDetail = (id) => {
  if (id === itemID.value) return;
  // 使用replace而不是push，避免在历史记录中堆积过多相似页面
  router.replace(`/secondhand/detail/${id}`);
};

// 监听路由参数变化，当itemID变化时重新获取数据
watch(() => route.params.id, (newId, oldId) => {
  if (newId !== oldId && route.params.id) {
    // 重置数据状态
    product.value = {};
    productImages.value = [];
    currentImage.value = '';
    sellerName.value = '';
    sellerAvatar.value = '';
    sellerCreditScore.value = 0;
    viewCount.value = 0;
    
    // 重新获取数据
    fetchProductDetail();
  }
}, { immediate: true });
</script>

<style lang="less" scoped>
.product-detail-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 24px;
}

.product-detail-wrapper {
  display: flex;
  gap: 40px;
  margin-bottom: 60px;
  
  @media (max-width: 768px) {
    flex-direction: column;
  }
}

.product-gallery {
  flex: 1;
  
  .main-image {
    width: 100%;
    height: 400px;
    background-size: cover;
    background-position: center;
    border-radius: 8px;
    margin-bottom: 16px;
  }
  
  .thumbnail-list {
    display: flex;
    gap: 12px;
    
    .thumbnail {
      width: 80px;
      height: 80px;
      background-size: cover;
      background-position: center;
      border-radius: 4px;
      cursor: pointer;
      border: 2px solid transparent;
      
      &.active {
        border-color: #ff2442;
      }
    }
  }
}

.product-info {
  flex: 1;
  
  .product-title {
    font-size: 24px;
    font-weight: 600;
    margin-bottom: 16px;
    color: #333;
  }
  
  .product-price {
    font-size: 28px;
    font-weight: 600;
    color: #ff2442;
    margin-bottom: 24px;
  }
  
  .product-meta {
    display: flex;
    flex-wrap: wrap;
    gap: 16px;
    margin-bottom: 24px;
    
    .meta-item {
      display: flex;
      align-items: center;
      color: #666;
      font-size: 14px;
      
      .el-icon {
        margin-right: 8px;
        color: #999;
      }
    }
  }
  
  .seller-info {
    display: flex;
    align-items: center;
    padding: 16px;
    background-color: #f9f9f9;
    border-radius: 8px;
    margin-bottom: 24px;
    
    .seller-avatar {
      width: 48px;
      height: 48px;
      border-radius: 50%;
      background-size: cover;
      background-position: center;
      margin-right: 16px;
    }
    
    .seller-details {
      .seller-name {
        font-size: 16px;
        font-weight: 500;
        color: #333;
        margin-bottom: 4px;
      }
      
      .seller-stats {
        font-size: 14px;
        color: #666;
        
        .rating {
          color: #ffba00;
        }
      }
    }
  }
  
  .divider {
    height: 1px;
    background-color: #eee;
    margin: 24px 0;
  }
  
  .product-description {
    margin-bottom: 32px;
    
    h3 {
      font-size: 18px;
      font-weight: 600;
      margin-bottom: 16px;
      color: #333;
    }
    
    p {
      font-size: 15px;
      line-height: 1.6;
      color: #666;
      margin-bottom: 20px;
    }
    
    .product-attributes {
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
      gap: 16px;
      
      .attribute {
        .label {
          font-size: 14px;
          color: #999;
          margin-right: 8px;
        }
        
        .value {
          font-size: 14px;
          color: #333;
        }
      }
    }
  }
  
  .action-buttons {
    display: flex;
    gap: 16px;
    
    button {
      display: flex;
      align-items: center;
      justify-content: center;
      padding: 12px 24px;
      border-radius: 8px;
      font-weight: 600;
      font-size: 16px;
      cursor: pointer;
      
      .el-icon {
        margin-right: 8px;
      }
      
      &:disabled {
        opacity: 0.6;
        cursor: not-allowed;
      }
    }
    
    .chat-button {
      background-color: white;
      color: #666;
      border: 1px solid #ddd;
      
      &:hover {
        background-color: #f5f5f5;
      }
    }
    
    .buy-button {
      background-color: #ff2442;
      color: white;
      border: none;
      flex: 1;
      
      &:hover:not(:disabled) {
        background-color: #e0203a;
      }
    }
  }
}

.related-products {
  .section-title {
    font-size: 20px;
    font-weight: 600;
    margin-bottom: 20px;
    color: #333;
  }
  
  .related-products-list {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
    gap: 20px;
    
    .related-product-item {
      background: #fff;
      border-radius: 8px;
      overflow: hidden;
      box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
      cursor: pointer;
      transition: transform 0.2s, box-shadow 0.2s;
      
      &:hover {
        transform: translateY(-3px);
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
      }
      
      .product-image {
        height: 160px;
        background-size: cover;
        background-position: center;
        position: relative;
        
        .product-price {
          position: absolute;
          bottom: 0;
          left: 0;
          background: rgba(255, 36, 66, 0.9);
          color: white;
          padding: 4px 12px;
          font-weight: bold;
          border-top-right-radius: 8px;
          font-size: 14px;
        }
      }
      
      .product-info {
        padding: 12px;
        
        .product-title {
          font-size: 14px;
          font-weight: 500;
          color: #333;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
      }
    }
  }
}
</style> 